<template>
  <div class="container">
    <!-- 添加或修改悬赏执行对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="头像" prop="offerAvatar">
          <el-upload
            name="offerFile"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="requestUpload"
            :before-upload="beforeAvatarUpload"
          >
            <el-avatar
              v-if="form.offerAvatar"
              :src="form.offerAvatar"
              size="large"
            ></el-avatar>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="悬赏编号" prop="offerCode">
          <el-input
            :disabled="isUpdate"
            v-model="form.offerCode"
            placeholder="请输入悬赏编号"
          />
        </el-form-item>
        <el-form-item label="被悬赏人类型" prop="offerModel">
          <el-radio-group v-model="form.offerModel">
            <el-radio
              :disabled="isUpdate"
              v-for="dict in dict.type.bus_offer_model"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="被悬赏人名称" prop="offerName">
          <el-input
            :disabled="isUpdate"
            v-model="form.offerName"
            placeholder="请输入被悬赏人"
          />
        </el-form-item>
        <el-form-item label="证件号码" prop="offerIdcard">
          <el-input
            :disabled="isUpdate"
            v-model="form.offerIdcard"
            placeholder="请输入证件号码"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            :disabled="isUpdate"
            v-model="form.mobile"
            placeholder="请输入手机号码"
          />
        </el-form-item>
        <el-form-item label="">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title"> 其他被执行人 </template>
              <div v-for="(item, index) in form.bouncer" :key="index">
                <el-divider></el-divider>
                <div v-if="item.offerModel == 2">
                  <p>类型：{{ item.offerModel }}</p>
                  <p>公司名称：{{ item.offerName }}</p>
                  <p>营业执照号：{{ item.offerIdcard }}</p>
                  <p>联系方式：{{ item.mobile }}</p>
                </div>
                <div v-else>
                  <p>类型：{{ item.offerModel }}</p>
                  <p>姓名：{{ item.offerName }}</p>
                  <p>身份证号：{{ item.offerIdcard }}</p>
                  <p>联系方式：{{ item.mobile }}</p>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
        <el-form-item label="案件执行地区" prop="city">
          <el-cascader
            style="width: 250px"
            :disabled="isUpdate"
            v-model="form.city"
            :options="cityOptions"
            :props="{ label: 'label', value: 'label' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="执行金额" prop="amount">
          <el-input
            type="number"
            :disabled="isUpdate"
            v-model="form.amount"
            placeholder="请输入执行金额"
          />
        </el-form-item>
        <el-form-item label="悬赏比例" prop="scale">
          <el-select
            :disabled="isUpdate"
            v-model="form.scale"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in scaleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审判法院" prop="court">
          <el-select
            :disabled="isUpdate"
            v-model="form.court"
            placeholder="审判法院"
            clearable
          >
            <el-option
              v-for="dict in dict.type.bus_court"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行进度" prop="schedule">
          <el-select
            :disabled="isUpdate"
            v-model="form.schedule"
            placeholder="执行进度"
            clearable
          >
            <el-option
              v-for="dict in dict.type.bus_schedule"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行案号" prop="executeNumber">
          <el-input
            :disabled="isUpdate"
            v-model="form.executeNumber"
            placeholder="请输入执行案号"
          />
        </el-form-item>
        <el-form-item label="案件描述" prop="description">
          <el-input
            :disabled="isUpdate"
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item
          label="生效判决书"
          prop="file1"
          v-if="
            form.schedule == '生效未执行' ||
            form.schedule == '首次执行' ||
            form.schedule == '恢复执行'
          "
        >
          <el-link
            v-for="(file, index) in file1_fileList"
            :key="index"
            type="primary"
            :underline="false"
            @click="downloadFile(file.url)"
            ><el-image
              v-if="checkFileType(file.url)"
              style="width: 50px; height: 50px"
              :src="file.url"
              fit="contain"
            ></el-image>
            <el-image
              v-else
              style="width: 50px; height: 50px"
              src="https://fast.dgsiy.com/wechat/images/pdficon.png"
              fit="contain"
            ></el-image>
          </el-link>
        </el-form-item>
        <el-form-item
          label="执行申请书"
          prop="file2"
          v-if="form.schedule == '首次执行' || form.schedule == '恢复执行'"
        >
          <el-link
            v-for="(file, index) in file2_fileList"
            :key="index"
            type="primary"
            :underline="false"
            @click="downloadFile(file.url)"
            ><el-image
              v-if="checkFileType(file.url)"
              style="width: 50px; height: 50px"
              :src="file.url"
              fit="contain"
            ></el-image>
            <el-image
              v-else
              style="width: 50px; height: 50px"
              src="https://fast.dgsiy.com/wechat/images/pdficon.png"
              fit="contain"
            ></el-image>
          </el-link>
        </el-form-item>
        <el-form-item
          label="受理通知书"
          prop="file3"
          v-if="form.schedule == '首次执行' || form.schedule == '恢复执行'"
        >
          <el-link
            v-for="(file, index) in file3_fileList"
            :key="index"
            type="primary"
            :underline="false"
            @click="downloadFile(file.url)"
            ><el-image
              v-if="checkFileType(file.url)"
              style="width: 50px; height: 50px"
              :src="file.url"
              fit="contain"
            ></el-image>
            <el-image
              v-else
              style="width: 50px; height: 50px"
              src="https://fast.dgsiy.com/wechat/images/pdficon.png"
              fit="contain"
            ></el-image>
          </el-link>
        </el-form-item>
        <el-form-item
          label="恢复执行书"
          prop="file4"
          v-if="form.schedule == '恢复执行'"
        >
          <el-link
            v-for="(file, index) in file4_fileList"
            :key="index"
            type="primary"
            :underline="false"
            @click="downloadFile(file.url)"
            ><el-image
              v-if="checkFileType(file.url)"
              style="width: 50px; height: 50px"
              :src="file.url"
              fit="contain"
            ></el-image>
            <el-image
              v-else
              style="width: 50px; height: 50px"
              src="https://fast.dgsiy.com/wechat/images/pdficon.png"
              fit="contain"
            ></el-image>
          </el-link>
        </el-form-item>
        <el-form-item
          label="裁定书"
          prop="file5"
          v-if="form.schedule == '终本'"
        >
          <el-link
            v-for="(file, index) in file5_fileList"
            :key="index"
            type="primary"
            :underline="false"
            @click="downloadFile(file.url)"
            ><el-image
              v-if="checkFileType(file.url)"
              style="width: 50px; height: 50px"
              :src="file.url"
              fit="contain"
            ></el-image>
            <el-image
              v-else
              style="width: 50px; height: 50px"
              src="https://fast.dgsiy.com/wechat/images/pdficon.png"
              fit="contain"
            ></el-image>
          </el-link>
        </el-form-item>
        <el-form-item label="跟进律师" prop="incharge">
          <el-select
            filterable
            v-model="form.incharge"
            placeholder="跟进律师"
            clearable
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="初审" prop="checked">
          <el-radio-group v-model="form.checked">
            <el-radio
              v-for="dict in dict.type.bus_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="复审" prop="repeatChecked">
          <el-radio-group v-model="form.repeatChecked">
            <el-radio
              v-for="dict in dict.type.bus_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="驳回原因"
          prop="reason"
          v-if="form.repeatChecked == 3"
        >
          <el-input
            type="textarea"
            v-model="form.reason"
            placeholder="请输入驳回原因"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_common_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- <el-form-item label="发布者签名" prop="remark">
          <el-link
            type="primary"
            :underline="false"
            @click="downloadFile(signimg)"
            ><el-image
              style="
                width: 350px;
                height: 250px;
                border: 1px solid #dddddd;
                border-radius: 4px;
              "
              :src="signimg"
              fit="contain"
            ></el-image>
          </el-link>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="loadAgreement">查看协议</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <el-dialog
        title="协议内容"
        :visible.sync="agreementOpen"
        width="800px"
        :append-to-body="true"
        :modal-append-to-body="true"
      >
        <div v-html="form.contractContent"></div>
        <div class="sign">
          <div class="signimg">
            <div>甲方：</div>
            <el-image
              style="width: 300px; height: 200px"
              :src="signimg"
              fit="contain"
            ></el-image>
          </div>
          <div class="signimg">
            <div>乙方：</div>
          </div>
        </div>
        <div class="sign">
        <div class="signimg">
          <div>丙方：</div>
        </div>
      </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import citys from "@/utils/city.js";
import { listUser, getUser } from "@/api/system/user";
import {
  getOffer,
  addOffer,
  updateOffer,
  uploadFile,
} from "@/api/business/offer";
export default {
  dicts: [
    "bus_court",
    "bus_schedule",
    "bus_progress",
    "bus_status",
    "bus_offer_model",
    "sys_common_status",
  ],
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 协议显示弹出层
      agreementOpen: false,
      agreementContent: "",
      address: "",
      // 表单参数
      form: {},
      signimg: '',
      userData: null,
      userList: [],
      cityOptions: [],
      scaleOptions: [
        {
          value: "15",
          label: "15%",
        },
        {
          value: "20",
          label: "20%",
        },
        {
          value: "25",
          label: "25%",
        },
        {
          value: "30",
          label: "30%",
        },
      ],
      isUpdate: true,
      file1_fileList: [],
      file2_fileList: [],
      file3_fileList: [],
      file4_fileList: [],
      file5_fileList: [],
      // 表单校验
      rules: {
        offerName: [
          { required: true, message: "被悬赏人不能为空", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.cityOptions = citys;
    this.getUserList();
  },
  methods: {
    /** 初始化表单 */
    async init(offerId) {
      this.open = true;
      this.reset();
      if (offerId) {
        await getOffer(offerId).then((response) => {
          const data = response.data;
          this.form = data;
          this.form.city = data.city !== null ? data.city.split("-") : "";
          this.form.bouncer = JSON.parse(data.bouncer);
          this.signimg = process.env.VUE_APP_BASE_API + data.signimg;
          if (data.file1) {
            const fileArr = data.file1.split(",");
            fileArr.forEach((item, index) => {
              const arr = item.split(":");
              this.file1_fileList.push({
                name: arr[0].split("/")[arr[0].split("/").length - 1],
                url: process.env.VUE_APP_BASE_API + arr[0],
              });
            });
          }
          if (data.file2) {
            const fileArr = data.file2.split(",");
            fileArr.forEach((item, index) => {
              const arr = item.split(":");
              this.file2_fileList.push({
                name: arr[0].split("/")[arr[0].split("/").length - 1],
                url: process.env.VUE_APP_BASE_API + arr[0],
              });
            });
          }
          if (data.file3) {
            const fileArr = data.file3.split(",");
            fileArr.forEach((item, index) => {
              const arr = item.split(":");
              this.file3_fileList.push({
                name: arr[0].split("/")[arr[0].split("/").length - 1],
                url: process.env.VUE_APP_BASE_API + arr[0],
              });
            });
          }
          if (data.file4) {
            const fileArr = data.file4.split(",");
            fileArr.forEach((item, index) => {
              const arr = item.split(":");
              this.file4_fileList.push({
                name: arr[0].split("/")[arr[0].split("/").length - 1],
                url: process.env.VUE_APP_BASE_API + arr[0],
              });
            });
          }
          if (data.file5) {
            const fileArr = data.file5.split(",");
            fileArr.forEach((item, index) => {
              const arr = item.split(":");
              this.file5_fileList.push({
                name: arr[0].split("/")[arr[0].split("/").length - 1],
                url: process.env.VUE_APP_BASE_API + arr[0],
              });
            });
          }
        });
        this.isUpdate = true;
        this.title = "查看操作";
      } else {
        this.isUpdate = false;
        this.title = "新增操作";
      }
    },
    /** 查询用户信息 */
    getUserData(userId) {
      getUser(userId).then((response) => {
        this.userData = response.data;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      listUser({ userModel: 3, status: 0 }).then((response) => {
        this.userList = response.rows;
      });
    },
    downloadFile(url) {
      const fileUrl = url; // 文件的URL地址
      window.open(fileUrl);
    },
    /** 提交按钮 */
    submitForm() {
      this.form.city = this.form.city[0] + "-" + this.form.city[1] + "-" + this.form.city[2];
      this.form.bouncer = JSON.stringify(this.form.bouncer);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.offerId != null) {
            updateOffer(this.form).then((response) => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
            });
          } else {
            addOffer(this.form).then((response) => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.isUpdate = false;
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isUpdate = false;
      this.reset();
    },
    // 检查文件类型
    checkFileType(file) {
      // 创建一个正则表达式对象，用于匹配常见的图片、视频等文件格式
      const regex = /^.*\.(jpg|jpeg|png|gif)$/i;

      if (regex.test(file)) {
        return true; // 如果符合条件返回true
      } else {
        return false; // 否则返回false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        offerId: null,
        offerCode: null,
        offerName: null,
        offerIdcard: null,
        mobile: null,
        city: null,
        amount: null,
        scale: null,
        court: null,
        schedule: null,
        description: null,
        file1: "",
        file2: "",
        file3: "",
        file4: "",
        file5: "",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.file1_fileList = [];
      this.file2_fileList = [];
      this.file3_fileList = [];
      this.file4_fileList = [];
      this.file5_fileList = [];
      this.resetForm("form");
    },
    requestUpload() {},
    /** 查看协议内容 */
    loadAgreement(newsId) {
      this.agreementOpen = true;
    },
    /** 头像上传 */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      let formData = new FormData();
      formData.append("offerFile", file);
      uploadFile(formData).then((response) => {
        this.form.offerAvatar = process.env.VUE_APP_BASE_API + response.imgUrl;
        this.$modal.msgSuccess("上传成功");
      });
      return isJPG && isLt2M;
    },
    /** 生效判决书上传 */
    file1BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      let formData = new FormData();
      formData.append("offerFile", file);
      uploadFile(formData).then((response) => {
        const arr =
          file.name + ":" + process.env.VUE_APP_BASE_API + response.imgUrl;
        this.file1_fileList.unshift({
          name: file.name,
          url: process.env.VUE_APP_BASE_API + response.imgUrl,
        });
        this.file1_fileList.forEach((_item) => {
          if (this.form.file1 == "") {
            this.form.file1 = arr;
          } else {
            this.form.file1 = this.form.file1 + "," + arr;
          }
        });
        this.$modal.msgSuccess("上传成功");
      });
      return isRightSize && isAccept;
    },
    /** 生效判决书删除 */
    file1OnRemove(file, fileList) {
      this.form.file1 = "";
      this.file1_fileList = fileList;
      this.file1_fileList.forEach((_item) => {
        const arr = _item.name + ":" + _item.url;
        if (this.form.file1 == "") {
          this.form.file1 = arr;
        } else {
          this.form.file1 = this.form.file1 + "," + arr;
        }
      });
    },

    /** 执行申请书上传 */
    file2BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      let formData = new FormData();
      formData.append("offerFile", file);
      uploadFile(formData).then((response) => {
        const arr =
          file.name + ":" + process.env.VUE_APP_BASE_API + response.imgUrl;
        this.file2_fileList.unshift({
          name: file.name,
          url: process.env.VUE_APP_BASE_API + response.imgUrl,
        });
        this.file2_fileList.forEach((_item) => {
          if (this.form.file2 == "") {
            this.form.file2 = arr;
          } else {
            this.form.file2 = this.form.file2 + "," + arr;
          }
        });
        this.$modal.msgSuccess("上传成功");
      });
      return isRightSize && isAccept;
    },

    /** 受理通知书上传 */
    file3BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      let formData = new FormData();
      formData.append("offerFile", file);
      uploadFile(formData).then((response) => {
        const arr =
          file.name + ":" + process.env.VUE_APP_BASE_API + response.imgUrl;
        this.file3_fileList.unshift({
          name: file.name,
          url: process.env.VUE_APP_BASE_API + response.imgUrl,
        });
        this.file3_fileList.forEach((_item) => {
          if (this.form.file3 == "") {
            this.form.file3 = arr;
          } else {
            this.form.file3 = this.form.file3 + "," + arr;
          }
        });
        this.$modal.msgSuccess("上传成功");
      });
      return isRightSize && isAccept;
    },

    /** 恢复执行书上传 */
    file4BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      let formData = new FormData();
      formData.append("offerFile", file);
      uploadFile(formData).then((response) => {
        const arr =
          file.name + ":" + process.env.VUE_APP_BASE_API + response.imgUrl;
        this.file4_fileList.unshift({
          name: file.name,
          url: process.env.VUE_APP_BASE_API + response.imgUrl,
        });
        this.file4_fileList.forEach((_item) => {
          if (this.form.file4 == "") {
            this.form.file4 = arr;
          } else {
            this.form.file4 = this.form.file4 + "," + arr;
          }
        });
        this.$modal.msgSuccess("上传成功");
      });
      return isRightSize && isAccept;
    },

    /** 裁定书上传 */
    file5BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      let formData = new FormData();
      formData.append("offerFile", file);
      uploadFile(formData).then((response) => {
        const arr =
          file.name + ":" + process.env.VUE_APP_BASE_API + response.imgUrl;
        this.file5_fileList.unshift({
          name: file.name,
          url: process.env.VUE_APP_BASE_API + response.imgUrl,
        });
        this.file5_fileList.forEach((_item) => {
          if (this.form.file5 == "") {
            this.form.file5 = arr;
          } else {
            this.form.file5 = this.form.file5 + "," + arr;
          }
        });
        this.$modal.msgSuccess("上传成功");
      });
      return isRightSize && isAccept;
    },
  },
};
</script>

<style lang="scss" scope>
.el-image__inner {
  padding-right: 10px;
}
.sign {
  display: table;
  .signimg {
    width: 50%;
    padding-right: 20px;
    display: table-cell;
  }
}
</style>